package com.roger.ndtplayer.base

import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import com.roger.ndtplayer.commom.bus.Bus
import com.roger.ndtplayer.commom.bus.USER_LOGIN_STATE_CHANGED

abstract class BaseVmActivity<VM : BaseViewModel> : BaseActivity() {

    protected open lateinit var mViewModel: VM

    override fun onCreate(savedInstanceState: Bundle?) {
        initViewModel()
        setContentView(layoutId)
        super.onCreate(savedInstanceState)
        observe()
    }

    /**
     * 初始化ViewModel
     */
    private fun initViewModel() {
        mViewModel =  ViewModelProvider(this, ViewModelProvider.NewInstanceFactory()).get(viewModelClass())
    }


    /**
     * 获取ViewModel的class
     */
    protected abstract fun viewModelClass(): Class<VM>

    /**
     * 订阅，LiveData、Bus
     */
    open fun observe() {
        // 登录失效，跳转登录页
        mViewModel.loginStatusInvalid.observe(this, {
            if (it) {
                Bus.post(USER_LOGIN_STATE_CHANGED, false)
//                ActivityHelper.startActivity(LoginActivity::class.java)
            }
        })
        mViewModel.showDialog.observe(this, {
            if (it) {
                showProgressDialog(mViewModel.dialogMsg.value.toString())
            } else {
                dismissProgressDialog()
            }
        })
    }


}
